package 多线程.安全.同步方法;

/**
 * @Projectname java_based
 * @Filename WindowTest5
 * @Author an
 * @Data 2022/7/12 9:06
 * @Description TODO
 */

class Windows5 extends Thread{

    private static int ticket = 100;

    @Override
    public void run() {
        while(show()){
//            show();

//            if(ticket > 0){
//
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//
//                System.out.println(getName() + ":卖票，票号为: " + ticket);
//                ticket--;
//            }else{
//                break;
//            }
        }
    }

    private static synchronized boolean show(){//同步监视器 window5.class
//    private synchronized void show(){//同步监视器 t1 t2 t3
        if(ticket > 0){

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

//            System.out.println(getName() + ":卖票，票号为: " + ticket);
            System.out.println(Thread.currentThread().getName() + ":卖票，票号为: " + ticket);
            ticket--;


            return true;
        }else {
            return false;
        }

    }
}

public class WindowTest5 {
    public static void main(String[] args) {
        Windows5 t1 = new Windows5();
        Windows5 t2 = new Windows5();
        Windows5 t3 = new Windows5();

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}
